package pers.vic.blog.schedule;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import pers.vic.blog.config.es.service.EsBlogArticleService;
import pers.vic.blog.module.api.model.BlogArticle;
import pers.vic.blog.module.api.service.BlogArticleService;
import pers.vic.boot.base.lookup.Lookup;

/**
 * @author Vic.xu
 * @description: 博文写入es的定时任务，可能在更换了index之后，需要执行一次的定时任务
 * @date: 2020/9/17 0017 8:47
 */
@Component
public class ArticleIntoEsSchedule {

    private static Logger logger = LoggerFactory.getLogger(ArticleIntoEsSchedule.class);

    @Value("${schedule.article2es.execute:false}")
    public boolean execute;

    @Autowired
    private EsBlogArticleService esBlogArticleService;

    @Autowired
    private BlogArticleService blogArticleService;
    /**
     * 1. 只执行一次
     * 2. 判断
     */
    @Scheduled(initialDelay = 10000, fixedRate = Long.MAX_VALUE)
    public void insertArticleToEs(){
        logger.info("进入博文写入es的定时任务(只执行一次), 本次是否执行：[{}]", execute);
        if(!execute){
            return;
        }
        Lookup lookup = new BlogArticle();
        final Integer[] count = {0};
        blogArticleService.list(lookup).stream().map(b->{
            count[0]++;
            return blogArticleService.findById(b.getId());
        }).forEach(esBlogArticleService::save);
        logger.info("博文写入es的定时任务处理的文章数目：[{}]", count[0]);
    }
}
